package LeetCode;

public class LeetCodeMain24 {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int[] arr=new int[gas.length];
        for (int i = 0; i < gas.length; i++) {
            arr[i]=gas[i]-cost[i];
        }
        int left=0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i]<0){
                left+=arr[i];
            }
            else{
                int flag=0;
                int sum=0;
                int j = i;
                for (; j < arr.length; j++) {
                    sum+=arr[j];
                    if (sum<0){
                        flag=-1;
                        break;
                    }
                }
                if (flag==0){
                    if (i==0){
                        return i;
                    }
                    sum+=left;
                    if (sum>=0){
                        return i;
                    }else {
                        left+=arr[i];
                    }
                }else {
                    left+=arr[i];
                }
            }
        }
        return -1;
    }
}
